﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;

namespace BBD_DAL.DBConnector
{
	public class DBConnection
	{
		private MySqlConnection connection;
		public DBConnection(string connectionString)
		{
			this.connection = new MySqlConnection(connectionString);
		}

		public void RunQuery(string query, MySqlParameter[] parameters)
		{
			MySqlCommand command = this.CreateCommand(query, parameters);
			this.Connect();
			command.ExecuteNonQuery();
			this.Disconnect();
		}

		public void RunQuery(string query, MySqlParameter[] parameters, out long id)
		{
			MySqlCommand command = this.CreateCommand(query, parameters);
			this.Connect();
			command.ExecuteNonQuery();
			id = command.LastInsertedId;
			this.Disconnect();
		}

		public void RunQuery(string query, MySqlParameter[] parameters, out DataTable dataTable)
		{
			MySqlCommand command = this.CreateCommand(query, parameters);
			dataTable = new DataTable();
			MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command);
			this.Connect();
			dataAdapter.Fill(dataTable);
			this.Disconnect();
		}

		private MySqlCommand CreateCommand(string query, MySqlParameter[] parameters)
		{
			MySqlCommand command = new MySqlCommand();

			command.Connection = connection;
			command.CommandText = query;
			if (parameters != null)
				command.Parameters.AddRange(parameters);
			command.CommandType = System.Data.CommandType.Text;

			return command;
		}

		public bool Connect()
		{
			try
			{
				this.connection.Open();
			}
			catch
			{
				return false;
			}

			return true;
		}

		public void Disconnect()
		{
			try
			{
				this.connection.Close();
			}
			catch
			{
			}
		}
	}
}
